import logging

import formencode
from formencode import validators
from formalchemy2.forms.config import ConfigForm
from formalchemy2.renderers.html5 import TextInput, HiddenInput
from formalchemy2.fields import Field

from pylons import config, request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect

from repoze.what.predicates import not_anonymous
from repoze.what.plugins.pylonshq import ActionProtector, ControllerProtector

from papyrus.lib.base import BaseController, render

log = logging.getLogger(__name__)

papyrus_conf = config["papyrus.config"]

class FormComments(formencode.Schema):
    """Represents the settings/comments form."""


class FormGeneral(formencode.Schema):
    """Represents the settings/general form."""
    allow_extra_fields = True
    filter_extra_fields = True

    blog_title = validators.String(not_empty=True)
    blog_tag = validators.String(not_empty=True)
    blog_description = validators.String(not_empty=True)
    blog_keywords = validators.String(not_empty=True)
    posts_per_page = validators.Int(min=1, not_empty=True)
    blog_copyright = validators.String(not_empty=True)

general_form = ConfigForm(papyrus_conf, sections=["general"],
                    default_renderer=TextInput(),
                    default_validator=str,
                    default_prettifyer=lambda x: x.replace("_", " ").capitalize())
hidden = Field("_method", value="PUT", renderer=HiddenInput())
general_form.append(hidden)


@ControllerProtector(not_anonymous())
class SettingsController(BaseController):

    def comments(self):
        """Comments settings."""
        return render("/admin/settings/comments.mako")

    def feeds(self):
        """Feeds settings."""
        return render("/admin/settings/feeds.mako")

    def general(self):
        """General settings."""
        c.form = general_form
        return render("/admin/settings/general.mako")

    def notifications(self):
        """Notifications settings."""
        return render("/admin/settings/notifications.mako")

    def widgets(self):
        """Widgets settings."""
        return render("/admin/settings/widgets.mako")

    def save_comments(self):
        """Save PUT data to configuration file."""
        redirect(url.current(action="comments"))

    def save_feeds(self):
        """Save PUT data to configuration file."""
        redirect(url.current(action="feeds"))

    def save_general(self):
        """Save PUT data to configuration file."""

        # Validate and sync config
        general_form.data = request.POST
        general_form.validate()
        general_form.sync(papyrus_conf)

        # Save configuration to file
        ini = config['papyrus.ini']
        with open(ini, "w") as f:
            papyrus_conf.write(f)

        redirect(url.current(action="general"))

    def save_notifications(self):
        """Save PUT data to configuration file."""
        redirect(url.current(action="notifications"))

    def save_widgets(self):
        pass
